package org.tp8.sampleapp.rule.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.kie.api.command.BatchExecutionCommand;
import org.kie.api.command.Command;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.internal.KnowledgeBase;
import org.kie.internal.command.CommandFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.tp8.sampleapp.exc.SampleAppException;
import org.tp8.sampleapp.rule.intf.RuleService;
import org.tp8.sampleapp.rule.model.RuleModelWrapper;
import org.tp8.sampleapp.service.abs.AbstractService;
import org.tp8.sampleapp.util.SampleAppLogger;

/**
 * The Class CourseServiceImpl.
 */
@Component("ruleService")
public class RuleServiceImpl extends AbstractService implements RuleService {

	/**
	 * The Constant log.
	 */
	public final static SampleAppLogger log = new SampleAppLogger(
			RuleServiceImpl.class);

	/** The app context. */
	@Resource
	private ApplicationContext appContext;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.tp8.sampleapp.rule.intf.RuleService#execute(java.lang.String,
	 * java.lang.Object)
	 */
	@Override
	public RuleModelWrapper execute(String knowledgeBase, Object entity)
			throws SampleAppException {

		// StatelessKieSession kSession = (StatelessKieSession) appContext
		// .getBean(sessionName);

		KnowledgeBase kb = (KnowledgeBase) appContext.getBean(knowledgeBase);

		RuleModelWrapper ruleModelWrapper = new RuleModelWrapper();
		ruleModelWrapper.setModel(entity);

		List<Command<?>> cmds = new ArrayList<Command<?>>();
		cmds.add(CommandFactory.newSetGlobal("log", log, true));
		cmds.add(CommandFactory.newInsert(ruleModelWrapper));
		cmds.add(CommandFactory.newInsert(entity));

		// Execute the list
		BatchExecutionCommand bec = CommandFactory.newBatchExecution(cmds);

		// synchronized (kSession) {
		StatelessKieSession kSession = kb.newStatelessKnowledgeSession();
		kSession.execute(bec);

		return ruleModelWrapper;
	}

}
